package com.stock_t.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.stock_t.entity.FundFlowHistory;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 东方财富资金流向工具类
 * 用于从东方财富网获取股票资金流向数据
 */
@Slf4j
public class EastMoneyFundFlowUtil {

    /**
     * 获取资金流向API
     */
    public static final String Fund_Flow_URL = "https://push2.eastmoney.com/api/qt/ulist.np/get?cb=jQuery112307430919154176441_1744950990656&fltt=2&secids={type}.{stockCode}&fields=f62%2Cf184%2Cf66%2Cf69%2Cf72%2Cf75%2Cf78%2Cf81%2Cf84%2Cf87%2Cf64%2Cf65%2Cf70%2Cf71%2Cf76%2Cf77%2Cf82%2Cf83%2Cf164%2Cf166%2Cf168%2Cf170%2Cf172%2Cf252%2Cf253%2Cf254%2Cf255%2Cf256%2Cf124%2Cf6%2Cf278%2Cf279%2Cf280%2Cf281%2Cf282&ut=b2884a393a59ad64002292a3e90d46a5&_=1744950990657";

    /**
     * 获取资金流历史数据
     */
    public static final String Fund_Flow_HISTROY_URL = "https://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get?cb=jQuery112309470556815196569_1744954698290&lmt=0&klt=101&fields1=f1%2Cf2%2Cf3%2Cf7&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61%2Cf62%2Cf63%2Cf64%2Cf65&ut=b2884a393a59ad64002292a3e90d46a5&secid={type}.{stockCode}&_=1744954698291";
    /**
     * 获取最新的涨跌幅
     */
    public static final String ZHANG_DIE_FU_URL = "https://push2.eastmoney.com/api/qt/ulist.np/get?fltt=2&fields=f2,f3&secids={type}.{stockCode}";

    /**
     * 公司的总市值
     */
    public static final String ZONG_SHI_ZHI_URL = "https://qt.gtimg.cn/q={type}{stockCode}";

    public static final String PEG = "https://datacenter-web.eastmoney.com/api/data/v1/get?callback=jQuery112301935672280176236_1747721642482&sortColumns=SECURITY_CODE&sortTypes=1&pageSize=6000&pageNumber=1&reportName=RPT_VALUEANALYSIS_DET&columns=ALL&quoteColumns=&source=WEB&client=WEB&filter=(TRADE_DATE%3D%27{date}%27)";


    public static final String GAI_NIAN = "https://push2.eastmoney.com/api/qt/clist/get?cb=jQuery112306530013565818652_1748312208187&fid=f62&po=1&pz=50&pn=1&np=1&fltt=2&invt=2&ut=8dec03ba335b81bf4ebdf7b29ec27d15&fs=b%3ABK0438&fields=f12%2Cf14%2Cf2%2Cf3%2Cf62%2Cf184%2Cf66%2Cf69%2Cf72%2Cf75%2Cf78%2Cf81%2Cf84%2Cf87%2Cf204%2Cf205%2Cf124%2Cf1%2Cf13";


//    public static void main(String[] args) {
//        Map<String, Object> map = fetchZhengDiefu("159967");
//        System.out.println("map = " + map);
//    }

    /**
     * 获取最新的涨跌幅
     */
    public static Map<String, Object> fetchZhengDiefu(String stockCode) {
        Map<String, Object> result = null;
        String html = "";
        try {
            result = new HashMap<>();
            String type = "0";
            if(stockCode.startsWith("5")) {
                type = "1";
            }
            String url = ZHANG_DIE_FU_URL.replace("{stockCode}", stockCode).replace("{type}", type);
            // 使用Hutool发送HTTP请求
            html = HttpUtils.get(url);
            // 提取JSON数据部分
            System.out.println("html: = " + html);
            JSONObject jsonObject = JSON.parseObject(html);
            // 提取有用的数据
            if (jsonObject != null && jsonObject.getInteger("rc") == 0) {
                JSONObject data = jsonObject.getJSONObject("data");
                data = (JSONObject) data.getJSONArray("diff").get(0);

                result.put("收盘价", new BigDecimal(data.getString("f2")));
                result.put("站跌幅", new BigDecimal(data.getString("f3")));
            }
        } catch (Exception e) {
            throw new RuntimeException("获取股价异常");
        }
        return result;
    }


    /**
     * 从东方财富网获取历史资金流向数据
     */
    public static List<Map<String, Object>> fetchFundFlowHistoryData(String stockCode) {
        List<Map<String, Object>> results = new ArrayList<>();
        String type = "0";
        if(stockCode.startsWith("5")) {
            type = "1";
        }
        String url = Fund_Flow_HISTROY_URL.replace("{stockCode}", stockCode).replace("{type}", type);
        // 使用Hutool发送HTTP请求
        String html = HttpUtils.get(url);
        // 提取JSON数据部分
        if (html != null && html.contains("(") && html.contains(")")) {
            int startIndex = html.indexOf("(") + 1;
            int endIndex = html.lastIndexOf(")");
            if (startIndex < endIndex) {
                String jsonStr = html.substring(startIndex, endIndex);
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                // 提取有用的数据
                if (jsonObject != null && jsonObject.getInteger("rc") == 0) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (data != null && data.containsKey("klines")) {
                        JSONArray klines = data.getJSONArray("klines");
                        for (int i = 0; i < klines.size(); i++) {
                            Map<String, Object> result = new HashMap<>();
                            String line = klines.getString(i);
                            String[] split = line.split(",");
                            result.put("日期", LocalDate.parse(split[0]));
                            result.put("收盘价", new BigDecimal(split[11]));
                            result.put("站跌幅", new BigDecimal(split[12]));
                            results.add(result);
                        }
                    }
                }
            }
        }
        return results;
    }

    /**
     * 将资金流向历史数据转换为实体对象
     *
     * @param stockCode 股票代码
     * @param dataMap   资金流向数据
     * @return FundFlowHistory对象
     */
    public static FundFlowHistory convertToFundFlowHistory(String stockCode, Map<String, Object> dataMap) {
        FundFlowHistory history = new FundFlowHistory();
        history.setStockCode(stockCode);

        // 设置交易日期
        history.setTradeDate((LocalDate) dataMap.get("日期"));
        // 设置价格和涨跌幅
        history.setClosePrice((BigDecimal) dataMap.get("收盘价"));
        history.setChangeRatio((BigDecimal) dataMap.get("站跌幅"));
        return history;
    }

}